// pages/login/login.js
Page({
  data: {
    usersID: '',
    Password: ''
  },
  onLoad: function() {
    const app = getApp();
    const usersID = app.globalData.usersID;
    if (usersID) {
      console.log('用户ID:', usersID);
    } else {
      console.log('用户未登录');
    }
  },
  inputUsername(e) {
    this.setData({
      usersID: e.detail.value
    });
  },
  inputPassword(e) {
    this.setData({
      Password: e.detail.value
    });
  },
  
  login() {
    const { usersID, Password } = this.data;
    if (!usersID || !Password) {
      wx.showToast({
        title: '请填写用户名和密码',
        icon: 'none'
      });
      return;
    }
    wx.cloud.callFunction({
      name: 'login',
      data: {
        usersID,
        Password
      },
      success: res => {
        if (res.result && res.result.success) {
          console.log('云函数返回的数据:', res.result);
          wx.showToast({
            title: '登录成功',
            icon: 'success'
          });
          // 存储用户信息到本地存储
          wx.setStorageSync('userId', res.result.usersId); // 直接存储用户ID
          console.log('存储的用户ID:', wx.getStorageSync('userId')); // 调试日志
          wx.setStorage({
            key: "userInfo",
            data: {
              usersID: res.result.usersId, // 存储用户ID
              nickname: res.result.nickname, // 从云函数返回的昵称
              openId: res.result.openId // 存储openId
            },
            success: function() {
              console.log("用户信息存储成功");
              console.log('存储的用户信息:', wx.getStorageSync('userInfo'));
            }
          });
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/index/index'
            });
          }, 1500);
        } else {
          wx.showToast({
            title: res.result ? res.result.message : '登录失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        wx.showToast({
          title: '登录请求失败',
          icon: 'none'
        });
        console.error('调用失败', err);
      }
    });
  },
  goToRegister: function() {
    wx.navigateTo({
      url: '/pages/register/register'
    });
  }
});
